package com.jfinal.plugin.radius.attribute;

import java.io.UnsupportedEncodingException;

/**
 * 这个类代表一个只包含字符串的Radius属性。
 */
public class StringAttribute extends RadiusAttribute {

    private String cachedValue;
    private int cachedHash;
    
	/**
	 * Constructs an empty string attribute.
	 */
	public StringAttribute() {
		super();
	}
	
	/**
	 * Constructs a string attribute with the given value.
	 * @param type attribute type
	 * @param value attribute value
	 */
	public StringAttribute(int type, String value) {
		setAttributeType(type);
		setAttributeValue(value);
	}
	
	/**
	 * Returns the string value of this attribute.
	 * @return a string
	 */
	public String getAttributeValue() {
	    byte[] b = getAttributeData();
	    int bhash = b.hashCode();
	    if (this.cachedValue == null || this.cachedHash != bhash) {
	        this.cachedValue = getAttributeValue(b);
	        this.cachedHash = bhash;
	    }
		return this.cachedValue;
	}
	
    /**
     * Returns the string value of the given attribute.
     * @param b the given attribute value.
     * @return a string
     */
	public static String getAttributeValue(byte[] b) {
        try {
            return new String(b, "UTF-8");
        } catch (UnsupportedEncodingException uee) {
            return new String(b);
        }
	}
	
	/**
	 * Sets the string value of this attribute.
	 * @param value string, not null
	 */
	public void setAttributeValue(String value) {
		if (value == null)
			throw new NullPointerException("string value not set");
		try {
			setAttributeData(value.getBytes("UTF-8"));
			this.cachedValue = value;
			this.cachedHash = getAttributeData().hashCode();
		} catch (UnsupportedEncodingException uee) {
			setAttributeData(value.getBytes());
		}
	}
	
}
